package com.zenchn.aliyun.oss.api.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.zenchn.aliyun.oss.api.OssSecurityTokenService;
import com.zenchn.entity.JsonResult;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * com.zenchn.aliyun.oss STS 安全令牌服务 实现类
 * @author dingxinfa
 * @date 2018-08-1
 *
 */
@Service
public class OssSecurityTokenServiceImpl implements OssSecurityTokenService {
	/**
	 * sts授权
	 */
	@Override
	public JsonResult<Map> getStsToken(String endpoint, String accessKeyId, String accessKeySecret,
                                       String roleSessionName, String roleArn, String policy, long durationSeconds) {
        JsonResult jsonResult=new JsonResult();
        try {
            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("", accessKeyId, accessKeySecret);

            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setSysEndpoint(endpoint);
            request.setSysMethod(MethodType.POST);
            request.setSysProtocol(ProtocolType.HTTPS);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName);
            request.setPolicy(policy); // Optional

            request.setDurationSeconds(durationSeconds);

            final AssumeRoleResponse response = client.getAcsResponse(request);

            Map<String, Object> restMap = new LinkedHashMap<String, Object>();
            restMap.put("accessKeyId", response.getCredentials().getAccessKeyId());
            restMap.put("accessKeySecret", response.getCredentials().getAccessKeySecret());
            restMap.put("securityToken", response.getCredentials().getSecurityToken());
            restMap.put("expiration", response.getCredentials().getExpiration());

            jsonResult.setSuccess(true);
            jsonResult.setCode(1);
            jsonResult.setData(restMap);
        } catch (ClientException e) {
            e.printStackTrace();
            Map<String, Object> restMap = new LinkedHashMap<String, Object>();
            restMap.put("errorCode", e.getErrCode());
            restMap.put("errorMessage", e.getErrMsg());
            restMap.put("requestId", e.getRequestId());
            jsonResult.setData(restMap);
            jsonResult.setSuccess(false);
            jsonResult.setCode(0);
        }

        return jsonResult;
	}
}
